package Controllers;

import DB.DBLocation;
import DB.DBRound;
import Models.Location;
import Models.Round;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class LocationController implements ControllerInterface<Location>
{
	public LocationController ()
	{}

	public int insert(Location location)
	{
		DBLocation dbl = new DBLocation();
		int locationNo = dbl.insert(location.exportData());

		location.setLocationNo(locationNo);
		location.setLocationNoOnRounds();
		insertDependent(location.getRounds());

		return locationNo;
	}

	public void insertDependent(ArrayList<? extends DB.RowInterface> data)
	{
		DBRound dbr = new DBRound();
		ArrayList<HashMap> rowsData = new ArrayList<HashMap>();
		Iterator<Round> i = ((ArrayList<Round>)data).iterator();
		while(i.hasNext())
		{
			Round round = i.next();
			if(dbr.alreadyExists(round.getRoundNo()))
			{
				dbr.update(round.exportData(), "roundNo = "+round.getRoundNo());
			}
			else
			{
				rowsData.add(round.exportData());
			}
			
		}
		dbr.insert(rowsData);
	}

	public Location find(int id)
	{
		DBLocation dbl = new DBLocation();
		return dbl.fetchByNo(id);
	}

	public int update(Location location, String where)
	{
		updateDependent(location.getRounds(), null);

		DBLocation dbl = new DBLocation();
		return dbl.update(location.exportData(), where);
	}

	public void updateDependent(ArrayList<? extends DB.RowInterface> data, String where)
	{
		DBRound dbr = new DBRound();
		Iterator<Round> i = ((ArrayList<Round>)data).iterator();
		while(i.hasNext())
		{
			Round round = i.next();
			if(dbr.alreadyExists(round.getRoundNo()))
			{
				dbr.update(round.exportData(), "roundNo = "+round.getRoundNo());
			}
			else
			{
				dbr.insert(round.exportData());
			}			
		}
	}

	public int delete(int id)
	{
		DBLocation dbl = new DBLocation();
		return dbl.deleteByNo(id);
	}

	public ArrayList<Location> fetchAll()
	{
		DBLocation dbl = new DBLocation();
		return dbl.fetchAll();
	}
}